﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

using Microsoft.Xna.Framework;


using Microsoft.Xna.Framework.Graphics;

namespace FXnaEngine.Components
{

    /// <summary>
    /// 暂时以此作为带有材质的模型的渲染系统
    /// </summary>
   public  class FSkinnedMeshRendererComponent:FRendererComponent
    {


       public FSkinnedMeshRendererComponent(FEntity parent,Model model)
           : base(parent)
       {


           this.model = model;
 

       }



       Model model;

       public Model Model
       {
           get { return model; }
           set { model = value; }
       }




       public override bool ExecuteMessage(IMessage message)
       {

           return false;
          
       }

       protected override void RenderCore(Graphics.FGraphicsSystem graphics)
       {
           base.RenderCore(graphics);

           

           foreach (ModelMesh mesh in model.Meshes)
           {
               Matrix world = mesh.ParentBone.Transform * Matrix.CreateScale(0.01f);

               BoundingSphere b= mesh.BoundingSphere.Transform(this.parentEntity.Transform.WorldMatrix);


               //如果不在相机可视范围内，就不用绘制了
               
               if (!b.Intersects (graphics.CurrentCamera.ViewFrustum))
               {
                   continue;
                   
               }


               foreach (ModelMeshPart part in mesh.MeshParts)
               {
                   BasicEffect myBasicEffect = part.Effect as BasicEffect;
                   myBasicEffect.World = world;
                   myBasicEffect.View = graphics. CurrentCamera.ViewMatrix;
                   myBasicEffect.Projection =graphics. CurrentCamera.ProjectionMatrix;

                   myBasicEffect.TextureEnabled = true;

                   foreach (EffectPass pass in myBasicEffect.CurrentTechnique.Passes)
                   {
                       pass.Apply();


                       graphics.GraphicsDevice.Indices = part.IndexBuffer;
                       graphics.GraphicsDevice.SetVertexBuffer(part.VertexBuffer);
                       graphics.GraphicsDevice.DrawIndexedPrimitives(PrimitiveType.TriangleList, part.VertexOffset, 0, part.NumVertices, part.StartIndex, part.PrimitiveCount);




                   }

                  

                  


               }



           }



       }
       



    }
}
